package com.jdk.learn.juc._06multithreadsecurity;

/**
 * Created by ricky
 * on 2018/1/31.
 *
 * 最基本的的生产者问题复现
 * 生产者消费者问题
 * 店员
 *
 */
public class TestProductAndConsumer {
    public static void main(String[] args) {
        Clerk clerk=new Clerk();
        Product product=new Product(clerk);
        Consumer consumer=new Consumer(clerk);

        new Thread(product,"生产者1").start();
        new Thread(consumer,"消费者1").start();
    }
}

/**
 * 售货员
 */
class Clerk{
    private int productnums=0;//产品数量

    /**
     * 拿货 取
     */
    public synchronized void get(){
        if (productnums >= 1) {//产品已满
            System.out.println("产品已满");
        } else {
            System.out.println(Thread.currentThread().getName() + ++productnums);
        }
    }
    /**
     * 卖货
     */
    public synchronized void sale(){
        if (productnums <= 0) {//产品缺货
            System.out.println("产品缺货");
        } else {
            System.out.println(Thread.currentThread().getName() + --productnums);
        }
    }
}


/**
 * 生产者
 */
class Product implements Runnable{
    private Clerk clerk;

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.get();
        }
    }
}


/**
 * 消费者
 */
class Consumer implements Runnable{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.sale();
        }
    }
}
